import cookesTools from  '@/mytools/cookesTools'  //从根目录找, 加@ 相当于从src目录开始找
import axios from 'axios'
import router from '@/router'
import {
  MessageBox,
  Message
} from 'element-ui'

// 创建一个axios对象, 默认给他接口的前缀连接
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL是axios内部封装的一个参数, 在执行时候 url = baseURL+ request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor   发起请求拦截器    类似于.net api的 过滤器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let token=cookesTools.getToken();
    if (token) {   //提取的token有效,  
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = token;  //header头中加入 X-Token=token
    }
    return config
  }
)


// 返回数据烂机器 使用axios拦截器来处理公共返回信息
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.status == 200) {
      // 获取返回结果
      const res = response.data
      // 如果结果不是成功的
      if (res.code !== 1) {
        if(res.code==50008)
        {

          MessageBox.confirm('您没有登录,请登录后在使用系统', {
            confirmButtonText: '跳转到登录页',
           
            type: 'warning'
          }).then(() => {
            router.push("/"); //跳转到登录页
          })
        }
        else{
          Message({
            message: res.mess || 'Error',
            type: 'error',
            duration: 5 * 1000 //显示5秒后自动关闭
          })
        }
        return Promise.reject(new Error(res.mess || 'Error')) //返回一个错误,终止访问
       
      } else {
        return res
      }
    } else {
      Message({
        message: "请求接口出现错误,请确认接口是否可以正常访问",
        type: 'error',
        duration: 5 * 1000 //显示5秒后自动关闭
      })
    }

  }

)

export default service
